import 'dart:convert';

class Product {
  int? id;
  String name = "";
  String description = "";
  int likeCount = 0;
  int viewCount = 0;
  String homeLink = '';
  String videoUrl = "";
  List<String> images = [];
  List<String> tags = [];

  List<String> vidoes = [];

  Product();

  static Product fromJson(Map<String, dynamic> json) {
    var attributes = json['data']['attributes'];
    Product product = Product();
    product.id = json['id'];
    product.name = attributes['name'];
    product.description = attributes['desc'] ?? "暂无内容";
    product.likeCount = attributes['like_count'] ?? 0;
    product.viewCount = attributes['view_count'] ?? 0;
    product.homeLink = attributes['test_link'] ?? "";
    product.videoUrl = attributes['video_link'] ?? "";
    List<Map<String, dynamic>> list =
        List<Map<String, dynamic>>.from(attributes['images']['data'] ?? []);
    List<String> images = [];
    for (var element in list) {
      images.add(element['attributes']['url']);
    }
    List<Map<String, dynamic>> tagList =
        List<Map<String, dynamic>>.from(attributes['tags']['data'] ?? []);
    List<String> tags = [];
    for (var element in tagList) {
      tags.add(element['attributes']['name']);
    }
    product.vidoes = parseFiles(attributes['video']['data']);
    product.tags = tags;
    product.images = images;
    return product;
  }

  static parseFiles(dynamic files) {
    List<String> list = [];
    if (files is Map) {
      list.add(files['attributes']['url']);
    } else if (files is List) {
      List<Map<String, dynamic>> vidoeList = List<Map<String, dynamic>>.from(files);
      for (var video in vidoeList) {
        list.add(video['attributes']['url']);
      }
    }
    return list;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['name'] = name;
    data['description'] = description;
    data['like_count'] = likeCount;
    data['view_count'] = viewCount;
    data['homeLink'] = homeLink;
    data['images'] = images;
    return data;
  }
}
